import os
from reportlab.lib import colors, pagesizes, units
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
    SimpleDocTemplate,
    Paragraph,
    Spacer,
    Table,
    TableStyle,
    PageBreak,
    Image as PdfImage
)

from book import Book, ContentType, TableContent
from utils import LOG


class Writer:
    def __init__(self):
        pass

    def save_translated_book(
        self, book: Book, output_file_path: str = None, file_format: str = "PDF"
    ):
        if file_format.lower() == "pdf":
            return self._save_translated_book_pdf(book, output_file_path)
        elif file_format.lower() == "markdown":
            return self._save_translated_book_markdown(book, output_file_path)
        else:
            raise ValueError(f"Unsupported file format: {file_format}")

    def _save_translated_book_pdf(self, book: Book, output_file_path: str = None):
        if output_file_path is None:
            output_file_path = book.pdf_file_path.replace(".pdf", f"_translated.pdf")

        LOG.info(f"pdf_file_path: {book.pdf_file_path}")
        LOG.info(f"开始翻译: {output_file_path}")

        # Register Chinese font
        font_path = "../fonts/simsun.ttc"  # 请将此路径替换为您的字体文件路径
        pdfmetrics.registerFont(TTFont("SimSun", font_path))

        # Create a PDF document
        doc = SimpleDocTemplate(output_file_path, pagesize=pagesizes.letter)
        styles = getSampleStyleSheet()
        story = []

        # Iterate over the pages and contents
        for page in book.pages:
            last_y = 0  # Starting y-position, e.g., from top margin
            for content in page.contents:
                # 当前块的坐标
                (current_x0, current_y0, current_x1, current_y1) = content.position

                # 第一行 或 第一块数据不需要插入间距
                if last_y != 0:
                    para_space = Spacer(width=0, height=spacing)
                    story.append(para_space)

                if content.content_type == ContentType.TEXT:
                    # 计算间距
                    spacing = current_y0 - last_y
                    # 设置字体样式
                    simsun_style = ParagraphStyle(
                        "SimSun", fontName="SimSun", fontSize=content.font_size
                    )
                    text = content.translation if content.status else content.original
                    para = Paragraph(text, simsun_style)
                    story.append(para)

                elif content.content_type == ContentType.TABLE:
                    # Add table to the PDF
                    pdf_table = self.gen_pdf_from_tables(content)
                    story.append(pdf_table)

                elif content.content_type == ContentType.IMAGE:
                    # Add table to the PDF
                    img = PdfImage(content.image_path)
                    img.drawHeight = content.height
                    img.drawWidth = content.width
                    story.append(img)
                last_y = current_y1

            # Add a page break after each page except the last one
            if page != book.pages[-1]:
                story.append(PageBreak())

        # Save the translated book as a new PDF file
        doc.build(story)
        LOG.info(f"翻译完成: {output_file_path}")
        return output_file_path

    def _save_translated_book_markdown(self, book: Book, output_file_path: str = None):
        if output_file_path is None:
            output_file_path = book.pdf_file_path.replace(".pdf", f"_translated.md")

        LOG.info(f"pdf_file_path: {book.pdf_file_path}")
        LOG.info(f"开始翻译: {output_file_path}")
        with open(output_file_path, "w", encoding="utf-8") as output_file:
            # Iterate over the pages and contents
            for page in book.pages:
                for content in page.contents:
                    if content.content_type == ContentType.TEXT:
                        # Add translated text to the Markdown file
                        text = content.translation if content.status else content.original
                        output_file.write(text + "\n\n")
                        
                    elif content.content_type == ContentType.TABLE:
                        # Add table to the Markdown file
                        output_file.write(content.generate_markdown_table(use_translation=True))
                        
                    elif content.content_type == ContentType.IMAGE:
                        # Add image to the Markdown file
                        output_file.write(f"![Image {content.image_name}]({content.image_name})\n\n")


                # Add a page break (horizontal rule) after each page except the last one
                if page != book.pages[-1]:
                    output_file.write("---\n\n")

        LOG.info(f"翻译完成: {output_file_path}")
        return output_file_path

    def gen_pdf_from_tables(self, tableContent):
        """
        根据解析的 TableContent 生成表格
        """
        # 提取每一行的数据
        data = []
        col_widths = []
        row_heights = []

        for row in tableContent.data:
            row_data = []

            # 如果 col_widths 为空，则初始化它
            if not col_widths:
                col_widths = [cell.width for cell in row.cells]

            for cell in row.cells:
                if cell.status:
                    row_data.append(cell.translation)
                else:
                    row_data.append(cell.original)

            data.append(row_data)
            row_heights.append(row.cells[0].heigth)  # 假设每个单元格高度相同

        # 创建表格
        table = Table(data, colWidths=col_widths, rowHeights=row_heights)

        # 设置表格样式
        table_style = TableStyle(
            [
                ("GRID", (0, 0), (-1, -1), 1, colors.black),
                ("ALIGN", (0, 0), (-1, -1), "CENTER"),
            ]
        )

        # 设置每个单元格的字体大小和颜色等属性
        for row_idx, row in enumerate(tableContent.data):
            for col_idx, cell in enumerate(row.cells):
                font_size = (
                    cell.font_size if cell.font_size else 10
                )  # 默认字体大小为 10
                is_bold = cell.is_bold if cell.is_bold else False
                font_name = "SimSun" if is_bold else "SimSun"
                table_style.add(
                    "FONTNAME", (col_idx, row_idx), (col_idx, row_idx), font_name
                )
                table_style.add(
                    "FONTSIZE", (col_idx, row_idx), (col_idx, row_idx), font_size
                )

        table.setStyle(table_style)

        return table
